package com.zym.application.utils;

import java.util.List;
import java.util.Map;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-01-29
 */
public abstract class Qs {
    public static final String LEFT_BTS = "%5B";//[
    public static final String RIGHT_BTS = "%5D";//]
    public static String stringify(Map<String, Object>  map){
        if(map == null){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            if(value instanceof Map){
                sb.append(getMap(entry.getKey(), (Map) entry.getValue()));

            }else if(value instanceof List) {
                sb.append(getArray(entry.getKey(),(List) entry.getValue()));
            }else {
                sb.append(entry.getKey() + "=" + entry.getValue());
                sb.append("&");
            }

        }
        sb.deleteCharAt(sb.lastIndexOf("&"));
        return sb.toString();
    }



    private static String getMap(String key,Map<String, Object>  map){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            if(value == null){
                sb.append(key).append(LEFT_BTS).append(entry.getKey()).append(RIGHT_BTS).append("=").append("&");
            }else {
                sb.append(key).append(LEFT_BTS).append(entry.getKey()).append(RIGHT_BTS).append("=").append(value).append("&");
            }
        }
        return sb.toString();
    }
    private static String getArray(String key,List   list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <list.size() ; i++) {
            Object o = list.get(i);
            if(o instanceof String){
                sb.append(key).append(LEFT_BTS).append(i).append(RIGHT_BTS).append("=").append((String)list.get(i)).append("&");
            }else if(o instanceof Map){
                Map<String, Object> map = (Map) o;
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Object value = entry.getValue();
                    //jsonBeans3[0][COST]=0
                    if(entry.getValue() == null){
                        Object value1 = entry.getValue();
                        value = "";
                    }
                    sb.append(key).append(LEFT_BTS).append(i).append(RIGHT_BTS).append(LEFT_BTS).append(entry.getKey()).append(RIGHT_BTS).append("=").append(entry.getValue()).append("&");
                }
            }

        }
        return sb.toString();
    }
}
